﻿using UnityEngine;

namespace CWM.Skinn
{
	public static class CanvasUtility
    {
		public static Color Vector3NormalizedColor(Vector3 delta)
        {
			float deltaSqrMagnitude = delta.sqrMagnitude;
			if (deltaSqrMagnitude == 0) return Color.white;
			delta.Normalize ();
			return Color.Lerp (Color.white,new Color (delta.x, delta.y, delta.z), deltaSqrMagnitude * 100000f);
		}

		public static Color Vector3NormalizedColor(Vector3 delta, float mag)
        {
			float deltaSqrMagnitude = delta.sqrMagnitude;
			if (deltaSqrMagnitude == 0)return Color.white;
			delta.x = (delta.x * 1500000f) / mag * 1f;
			delta.y = (delta.y * 1500000f) / mag * 1f;
			delta.z = (delta.z * 1500000f) / mag * 1f;
			delta = Vector3.ClampMagnitude (delta, 1f);
			return Color.Lerp (Color.white,new Color (delta.x, delta.y, delta.z), deltaSqrMagnitude * mag * 1500000f);
		}

		public static bool IsBackFace(Vector3 normal, Transform transform)
		{
			if (Vector3.Dot (transform.rotation * normal, Camera.current.transform.forward) <= 0) return false;
			return true;
		}

		public static int RayCrossHit(Ray ray , Mesh mesh, Transform transform, float magnitude){
			int closestIndex = -1;
			float minMagnitude = Mathf.Infinity;
			Vector3[] positions = mesh.vertices;
			Vector3[] normals = mesh.normals;

			for (int i = 0; i < positions.Length; i++)
            {
				if (IsBackFace (normals [i], transform)) continue;
				Vector3 distance = transform.TransformPoint(positions [i]) - ray.origin;
				float directionMagnitude = Vector3.Cross (distance, ray.direction).magnitude;
				if (directionMagnitude < magnitude & directionMagnitude < minMagnitude)
                {
					minMagnitude = directionMagnitude;
					closestIndex = i;
				}
			}
			return closestIndex;
		}

		public static Vector3 MirrorX(Transform transform, Vector3 worldPoint)
        {
			Vector3 localPoint = transform.InverseTransformPoint (worldPoint);
			localPoint.x = -localPoint.x;
			return transform.TransformPoint (localPoint);
		}
    }
}